package com.aloda.task;

import com.aloda.cache.RedisUtils;
import com.aloda.entity.AppBrowse;
import com.aloda.service.AppBrowseService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 应用的定时任务
 */
@Slf4j
@Component
public class AppTask {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private AppBrowseService appBrowseService;

    /**
     * 每日0点重置app浏览记录排行榜,并将今日数据落库
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void setAppBrowse() {
        List<AppBrowse> appBrowses = appBrowseService.getAllAppBrowse();
        if (appBrowses.isEmpty()) {
            log.info("今日无应用浏览记录");
            return;
        }
        // 3.数据持久化
        try {
            appBrowseService.saveBatch(appBrowses);
            log.info("应用浏览记录数据持久化成功");
        } catch (Exception ex) {
            log.warn("应用浏览记录数据持久化失败");
        } finally {
            Boolean delete = redisUtils.deleteAppBrowse();
            if (Boolean.TRUE.equals(delete)) {
                log.info("重置app浏览记录排行榜成功");
            } else {
                log.warn("重置app浏览记录排行榜失败");
            }
        }
    }
}
